package com.example.service.impl.report;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.result.PageResult;
import com.example.entity.dto.MouldReportDto;
import com.example.entity.dto.WorkReportDto;
import com.example.entity.excel.MouldReportExcel;
import com.example.entity.mysql.Resource;
import com.example.entity.vo.*;
import com.example.entity.vo.weixiubaoyang.MouldReportVo;
import com.example.exception.CustomException;
import com.example.mapper.report.ReportMapper;
import com.example.service.pc.ResourceService;
import com.example.service.report.ReportService;
import com.example.untils.BeanUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ResourceService resourceService;
    /**
     * 工单报表
     * @param dto
     * @return
     */
    @Override
    public PageResult workOrderPage(WorkReportDto dto) {
        // 设置分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        // 分页条件查询
        Page<WorkReportVo> workOrderList = reportMapper.pageWorkOrder(dto);

        return new PageResult(workOrderList.getTotal(),workOrderList.getResult());
    }

    /**
     * 模具履历报表
     * @return
     */
    @Override
    public MouldReportVo mouldReport(MouldReportDto dto) {
        if(dto.getDeviceid().isEmpty() || dto.getDeviceid() == ""){
            throw new CustomException("500","查询设备编号不能为空");
        }
        MouldReportVo mouldReportVo = new MouldReportVo();
        //模具基本
        MbaVo mbaVo = new MbaVo();
        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>()
                        .eq(Resource::getDeviceid,dto.getDeviceid()));
        if(resource != null) {
            BeanUtils.copyPropertiesIgnoreCase(resource,mbaVo);
        }
        mouldReportVo.setMbavo(mbaVo);

        //模具变动
        List<McVo> mcVoList = reportMapper.selectMouldChange(dto.getDeviceid());
        mouldReportVo.setMcVoList(mcVoList);

        //模具保养
        List<MbVo> mbVoList  = reportMapper.selectMouldMaintain(dto.getDeviceid());
        mouldReportVo.setMbVoList(mbVoList);

        //模具维修
        List<MxVo> mxVoList = reportMapper.selectMouldRepair(dto.getDeviceid());
        mouldReportVo.setMxVoList(mxVoList);
        return mouldReportVo;
    }

    @Override
    public void exportMould(MouldReportDto dto, HttpServletResponse response) {
        //响应内容格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + dto.getDeviceid() + "履历报表.xlsx");

        MouldReportVo vo = mouldReport(dto);

        MouldReportExcel.MbaExcel mbaExcel=new MouldReportExcel.MbaExcel();
        org.springframework.beans.BeanUtils.copyProperties(vo.getMbavo(),mbaExcel);
        String type;
        switch (vo.getMbavo().getResourceType()){
            case 1:
                type="设备";
                break;
            case 2:
                type="生产线";
                break;
            case 3:
                type="模具";
                break;
            case 4:
                type="工装";
                break;
            default:
                type="异常类型";
        }
        mbaExcel.setResourceType(type);

        //模具变动
        List<MouldReportExcel.McExcel> mcExcels = vo.getMcVoList().stream().map(item -> {
            MouldReportExcel.McExcel excel = new MouldReportExcel.McExcel();
            org.springframework.beans.BeanUtils.copyProperties(item, excel);
            return excel;
        }).collect(Collectors.toList());

        //模具保养
        List<MouldReportExcel.MbExcel> mbExcels = vo.getMbVoList().stream().map(item -> {
            MouldReportExcel.MbExcel excel = new MouldReportExcel.MbExcel();
            org.springframework.beans.BeanUtils.copyProperties(item, excel);
            String te019="";
            switch (item.getTE019()) {
                case "0":
                    te019 = "未执行";
                    break;
                case "1":
                    te019 = "完成";
                    break;
                case "2":
                    te019 = "未完成结束";
                    break;
            }
            excel.setTE019(te019);
            return excel;
        }).collect(Collectors.toList());

        //模具维修
        List<MouldReportExcel.MxExcel> mxExcels = vo.getMxVoList().stream().map(item -> {
            MouldReportExcel.MxExcel excel = new MouldReportExcel.MxExcel();
            org.springframework.beans.BeanUtils.copyProperties(item, excel);
            return excel;
        }).collect(Collectors.toList());

        File temp1;
        File temp2;
        try {
            temp1 = File.createTempFile("temp1", ".xlsx");
            temp2 = File.createTempFile("temp2", ".xlsx");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //写入基本资料
        EasyExcel.write(temp1, MouldReportExcel.MbaExcel.class).sheet("sheet1")
                .doWrite(Collections.singletonList(mbaExcel));
        //写入模具变动
        EasyExcel.write(temp2,MouldReportExcel.McExcel.class).withTemplate(temp1).sheet("sheet1")
                .doWrite(mcExcels);
        //写入模具保养
        EasyExcel.write(temp1,MouldReportExcel.MbExcel.class).withTemplate(temp2).sheet("sheet1")
                .doWrite(mbExcels);
        //写入模具维修
        EasyExcel.write(temp2,MouldReportExcel.MxExcel.class).withTemplate(temp1).sheet("sheet1")
                .doWrite(mxExcels);

        byte[] bytes = null;
        try (FileInputStream fis = new FileInputStream(temp2)) {
            bytes = new byte[(int) temp2.length()];
            fis.read(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        temp1.deleteOnExit();
        temp2.deleteOnExit();
        try {
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
